<template>
	<div class="login">
		<h1>电力巡检系统</h1>
		<div class="form-group">
			<label for="usercode">账户:</label>
			<input type="text" v-model="PsUser.usercode" />
		</div>
		<div class="form-group">
			<label for="userpassword">密码:</label>
			<input type="password" v-model="PsUser.userpassword" />
		</div>
		<button @click="logins()" class="btn btn-warning">登录</button>&nbsp;&nbsp;&nbsp;
		<!-- <button @click="register()" class="btn btn-success">注册</button> -->
	</div>
</template>

<script>
	import axios from 'axios'
	import {
		loginQuery,
		addPsLog,
		PersonalDataUpd
	} from '../config/request.js'
	export default {
		data() {
			return {
				PsUser: {
					usercode: 'admin',
					userpassword: '123456'
				},
				PsUsers:{
					id:'',
					lastlogintime:'',
					userpassword: ''
				},
				psLogs: {
					usercode: '',
					username: '',
					operateinfo: '登录操作',
					operatedatetime: '',
				}
			}
		},
		methods: {
			formatDateTime(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			logins() {
				loginQuery(this.PsUser).then(json => {
					if (json == "no") {
						alert("账号或密码错误")
					} else {
						const currentDate = new Date();
						const formattedDate = this.formatDateTime(currentDate);
						this.PsUsers.id = json.id;
						this.PsUsers.userpassword = json.userpassword;
						//存入到session
						sessionStorage.setItem('psUser', JSON.stringify(json));
						this.psLogs.usercode = this.PsUser.usercode;
						this.psLogs.username = json.username;
						this.psLogs.operatedatetime = formattedDate;
						//记录登录日志
						addPsLog(this.psLogs).then(json => {
						})
						this.PsUsers.lastlogintime = formattedDate;
						//修改最后登录时间
						PersonalDataUpd(this.PsUsers).then(json=>{})
						this.$router.push('/Main')
					}
				})
			},
			register() {
				this.$router.push("/Register")
			}
		}
	};
</script>

<style scoped>
	.login {
		max-width: 500px;
		margin: 0 auto;
		padding: 30px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.login h1 {
		text-align: center;
	}

	.form-group {
		margin-bottom: 10px;
	}

	label {
		display: block;
		font-weight: bold;
	}

	input[type="text"],
	input[type="password"] {
		width: 100%;
		padding: 5px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}
</style>